<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { Dialog, Toast } from "vant";
import { genderArray } from "@/constants";
import useUserStore from "@/pinia/modules/userStore/userStore.ts";
import type { Patient } from "@/types/userTypes/userTypes.ts";
import type { Ref, ComputedRef } from "vue";
import type { RouteLocationNormalized, Router } from "vue-router";

import useConsultStore from "@/pinia/modules/consultStore/consultStore.ts";

const userStore = useUserStore();

const consultStore = useConsultStore();

const router: Router = useRouter();

const route: RouteLocationNormalized = useRoute();

const { patientList } = storeToRefs(userStore);

const { consult } = storeToRefs(consultStore);

const showPopup: Ref<boolean> = ref<boolean>(false);

const edit: Ref<boolean> = ref<boolean>(false);

const selectPatientId = ref<string>("");

const navBarTitle: ComputedRef<string> = computed<string>(() => edit.value ? "编辑患者" : "添加患者");

const isSelectPatient: ComputedRef<boolean> = computed<boolean>(() => route.query.selectPatient === "true");


const patientData = reactive<Patient>({
   name: "",
   idCard: "",
   defaultFlag: 0,
   gender: 1,
});

const defaultPatient: Ref<boolean> = ref<boolean>(false);

const addPatient = (): void => {
   edit.value = false;
   showPopup.value = true;
};

const editPatient = (patient: Patient): void => {
   edit.value = true;
   showPopup.value = true;
   Object.assign(patientData, { name: patient.name, idCard: patient.idCard, id: patient.id, gender: patient.gender, defaultFlag: patient.defaultFlag });
   defaultPatient.value = patient.defaultFlag === 1;
};

const deletePatient = async (patient: Patient) => {
   const confirm = await Dialog.confirm({ title: "提示", message: `确定删除${patient.name}患者吗?` }).catch(error => error);
   if (confirm === "cancel") return;
   await userStore.deletePatient(patient.id as string);
};

const handleSave = async () => {
   if (patientData.id) delete patientData.id;
   if (edit.value) {
      try {
         const updateResult = await userStore.updatePatient(patientData);
         await userStore.fetchPatientList();
         showPopup.value = false;
         Toast.success(updateResult);
      } catch (error: any) {
         Toast.fail(error.message);
      }
   } else {
      try {
         const addResult = await userStore.addPatient(patientData);
         await userStore.fetchPatientList();
         showPopup.value = false;
         Toast.success(addResult);
      } catch (error: any) {
         Toast.fail(error.message);
      }
   }
};

const changeSelectPatientId = (patient: Patient) => {
   if (!isSelectPatient.value) return;
   selectPatientId.value = patient.id as string;
};

const next = () => {
   if (!selectPatientId.value) return Toast.fail("选择就诊患者");
   consultStore.setPatientId(selectPatientId.value);
   router.push("/consult/pay")
};

watch(defaultPatient, (newValue: boolean) => {
   patientData.defaultFlag = newValue ? 1 : 0;
});

onMounted(() => {
   userStore.fetchPatientList();
   nextTick(()=>{
     setTimeout(()=>{
        if (!isSelectPatient.value) return;
        if (selectPatientId.value) return;
        const deuatltPatient: Patient | undefined = patientList.value.find(item => item.id === selectPatientId.value);
        if (deuatltPatient) {
           selectPatientId.value = deuatltPatient.id as string;
        } else {
           if (consult.value.patientId) {
              selectPatientId.value = consult.value.patientId;
           } else {
              selectPatientId.value=patientList.value[0]?.id as string
           }
        }
     },500)
   })
});

watch(showPopup, (newValue: boolean) => {
   if (!newValue) {
      Object.assign(patientData, { name: "", idCard: "", defaultFlag: 0, gender: 1 });
      defaultPatient.value = false;
   }
});

</script>

<template>
   <div class="patient-page">
      <nav-bar :title="isSelectPatient?'选择患者':'患者列表'" left-arrow left-text="返回" @click-left="$router.back()"></nav-bar>
      <div class="patient-change" v-if="isSelectPatient">
         <h3>请选择患者信息</h3>
         <p>以便医生给出更准确的治疗，信息仅医生可见</p>
      </div>
      <div class="patient-list">
         <div class="patient-item" :class="{selected:item.id===selectPatientId}" v-for="(item) in patientList" @click="changeSelectPatientId(item)">
            <div class="info">
               <span class="name">{{ item.name }}</span>
               <span class="id">{{ item.idCard.replace(/^(.{6}).+(.{4})$/, "\$1********\$2") }}</span>
               <span>{{ item.genderValue }}</span>
               <span>{{ item.age }}岁</span>
            </div>
            <div class="icon" @click="editPatient(item)" v-if="!isSelectPatient">
               <svg-icon svg-name="edit" />
            </div>
            <div class="delete" @click="deletePatient(item)" v-if="!isSelectPatient">
               <svg-icon svg-name="delete" width="25px" height="25px"></svg-icon>
            </div>
            <div class="tag" v-if="item.defaultFlag===1">默认</div>
         </div>
         <div class="patient-add" v-if="patientList.length<=10&&!isSelectPatient">
            <svg-icon svg-name="add" />
            <p @click="addPatient">添加患者</p>
         </div>
         <van-button type="primary" block round v-if="isSelectPatient" @click="next">下一步</van-button>
      </div>

      <van-popup v-model:show="showPopup" position="right">
         <nav-bar left-text="返回" :title="navBarTitle" right-text="保存" @click-left="showPopup=false" @click-right="handleSave"></nav-bar>
         <van-form ref="formRef">
            <van-field label="真实姓名" placeholder="请输入真实姓名" v-model="patientData.name"></van-field>
            <van-field label="身份证号" placeholder="请输入身份证号" v-model="patientData.idCard"></van-field>
            <van-field label="性别" class="pb4">
               <template #input>
                  <RadioBtn :options="genderArray" v-model="patientData.gender"></RadioBtn>
               </template>
            </van-field>
            <van-field label="默认就诊人">
               <template #input>
                  <van-checkbox :icon-size="18" round v-model="defaultPatient" />
               </template>
            </van-field>
         </van-form>
      </van-popup>
   </div>
</template>

<style lang="scss" scoped>
.patient-page {
   .patient-change {
      padding: 15px;

      > h3 {
         font-weight: normal;
         margin-bottom: 5px;
      }

      > p {
         color: var(--cp-text3);
      }
   }

   .patient-next {
      padding: 15px;
      background-color: #fff;
      position: fixed;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 80px;
      box-sizing: border-box;
   }

   .patient-list {
      padding: 15px;
   }

   .patient-item {
      display: flex;
      align-items: center;
      padding: 15px;
      background-color: var(--cp-bg);
      border-radius: 8px;
      margin-bottom: 15px;
      position: relative;
      border: 1px solid var(--cp-bg);
      transition: all 0.3s;
      overflow: hidden;

      .info {
         display: flex;
         flex-wrap: wrap;
         flex: 1;

         span {
            color: var(--cp-tip);
            margin-right: 20px;
            line-height: 30px;

            &.name {
               font-size: 16px;
               color: var(--cp-text1);
               width: 80px;
               margin-right: 0;
            }

            &.id {
               color: var(--cp-text2);
               width: 180px;
            }
         }
      }

      .icon {
         color: var(--cp-tag);
         width: 20px;
         text-align: center;
      }

      .tag {
         position: absolute;
         right: 60px;
         top: 21px;
         width: 30px;
         height: 16px;
         font-size: 10px;
         color: #fff;
         background-color: var(--cp-primary);
         border-radius: 2px;
         display: flex;
         justify-content: center;
         align-items: center;
      }

      .delete {
         position: absolute;
         right: 0;
         top: 0;
      }

      &.selected {
         border-color: var(--cp-primary);
         background-color: var(--cp-plain);

         .icon {
            color: var(--cp-primary);
         }
      }
   }

   .patient-add {
      background-color: var(--cp-bg);
      color: var(--cp-primary);
      text-align: center;
      padding: 15px 0;
      border-radius: 8px;

      .cp-icon {
         font-size: 24px;
      }
   }

   .patient-tip {
      color: var(--cp-tag);
      padding: 12px 0;
   }

   .pb4 {
      padding-bottom: 4px;
   }

   :deep(.van-popup) {
      width: 100%;
      height: 100%;
   }
}

</style>
